package com.securite.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Description: TODO(自己定义用户名和密码)
 * @Author da
 * @Date 2021/10/24 上午 10:56
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService
{

    @Autowired
    private PasswordEncoder passwordEncoder; // 这里注入配置类配置的密码解析类

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        System.out.println("执行了自定义的用户验证");
//        根据用户名查询数据库,如果不存在就抛出UsernameNotFoundException
//        这里不查数据库,直接用admin模拟查出的数据
        if (!"admin".equals(username))
        {
            throw new UsernameNotFoundException("用户名不存在");
        }
//        比较密码(注册时密码已经加密过),如果匹配成功返回UserDetails
        String password = passwordEncoder.encode("123");

        return new User(username, password,
                //AuthorityUtils.commaSeparatedStringToAuthorityList(角色)
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));
    }
}
